package com.mb.mp.util;

import com.mb.common.utils.DateUtils;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Date;

/**
 * 图片水印处理
 *
 * @author michael.li
 * @create 2018-04-09 下午5:15
 **/
public class WaterMarkUtils {

    /**
     * 添加水印文字
     * @param picUrl
     * @param outPicUrl
     * @param fontText
     */
    public static void addWaterMark(String picUrl,String outPicUrl, String fontText) {

        try {
            //获取模板文件
            BufferedImage tplImg = ImageIO.read(new File(picUrl));
            int width = tplImg.getWidth();//图片宽度
            int height = tplImg.getHeight();//图片高度
            System.out.println("srcImgWidth :"+width);
            System.out.println("srcImgHeight :"+height);

            BufferedImage combined = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
            Graphics g = combined.getGraphics();
            //合并模板
            g.drawImage(tplImg, 0, 0, null);

            g.setColor(Color.red);
            Font font = new Font("微软雅黑", Font.PLAIN, 30);// 添加字体的属性设置
            // 设置文本样式
            g.setFont(font);
            // 添加水印
            g.drawString(fontText, width - 360, height - 130);
            g.dispose();
            // 获取新文件的地址
            File outputfile = new File(outPicUrl);
            //写入新图片
            ImageIO.write(combined, getSuffix(picUrl), outputfile);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }



    public static String getSuffix(String picUrl){
        File file = new File(picUrl);
        String fileName = file.getName();
        String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
        return suffix;
    }

    public static void main(String[] args) {
        String picUrl = "/Users/michaelli/Downloads/WechatIMG2.jpeg";
        String outPicUrl = "/Users/michaelli/Downloads/WechatIMG2_new.jpeg";
        String fontText = DateUtils.format(new Date(),"yyyy-MM-dd HH:mm:ss");
        //addWaterMark(picUrl,outPicUrl,fontText);
        addWaterMark(picUrl,outPicUrl,fontText);
    }

}
